/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      qiNiuUpload
 * @Description:    七牛云上传组件
 * @Author:         SuPeiSen
 * @CreateDate:     2021/1/28 10:37 上午
 * @UpdateDate:     2021/1/28 10:37 上午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import React, { useEffect, useState } from 'react';
import { getQiNiuUploadTokenApi } from '@/service/upload_api';
import { Button, Upload } from 'antd';
import { AppConfig } from '@/config/app_config';
import { UploadOutlined } from '@ant-design/icons';
import { UploadFile } from 'antd/lib/upload/interface';

/**
 * 文章图片
 * @constructor
 */
export const QiNiuUploadWidget = (props: {
  onSelect: (url: string) => void;
  initValue?: Array<UploadFile>;
}) => {
  const [uploadToken, setUploadToken] = useState<string>('');
  useEffect(() => {
    getQiNiuUploadTokenApi().then((value) => {
      if (value !== undefined) {
        setUploadToken(value);
      }
    });
  }, []);

  return (
    <Upload
      defaultFileList={props.initValue}
      action="http://up-z2.qiniup.com"
      listType="picture"
      beforeUpload={(file, fileList) => {
        return true;
      }}
      onPreview={(file) => {
        if (file.response !== undefined && file.response.code === 200) {
          window.open(AppConfig.ImageDoMain + file.response.data.key);
        } else {
          window.open(file.url);
        }
      }}
      data={{ token: uploadToken }}
      onChange={(info) => {
        if (info.file.status === 'done') {
          props.onSelect(info.file.response.data.key);
        }
      }}
    >
      <Button icon={<UploadOutlined />}>上传图片</Button>
    </Upload>
  );
};
